package com.hrbxlh.actionImpl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hrbxlh.action.ProblemAction;
import com.hrbxlh.dao.*;
import com.hrbxlh.pojo.SysUser;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.SessionValues;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.util.pageUtil;

import static com.hrbxlh.support.web.auth.constant.ServiceConstant.USER_INFO;


@Component("problemActionImpl")
@Transactional
public class ProblemActionImpl {

	@Resource(name="problemDao")
	private ProblemDao problemDao;

	@Resource(name="courseDao")
	private CourseDao courseDao;

	@Resource(name="answerDao")
	private AnswerDao answerDao;

	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;

	@Resource(name = "memberDao")
	private MemberDao memberDao;
	//日志信息
	Logger logger = Logger.getLogger(ProblemActionImpl.class.getName());

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  问题列表页面（教师）。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllProblemList(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//查询当前登陆人的基本信息
			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("excuseMark",memList.get(0).get("excuseMark"));
			//通过教师号获取此教师所属课程
			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
			if(courseList!=null&&courseList.size()!=0){
				returnMap.put("courseList", courseList);
				paramMap.put("courseList", courseList);


				//查询问题列表(查询每个习题中回答的个数20171218改--回答问题的个数不从数据库中取，改成计算)
				List<Map<String, Object>> problemList = problemDao.getAllProblemList(paramMap);
				returnMap.put("problemList", problemList);
				returnMap.put("pageNow", pageNow);

				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = problemDao.getAllProblemList(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
				returnMap.put("errFlag", "success");
			}else{
				returnMap.put("errFlag", "fail");
				returnMap.put("errMsg", "当前课程暂无问题");
			}

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  我的问题列表
	 * @throws IOException
	 */
	public Map<String, Object> getMyProblemListByPost(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//查询问题列表
			List<Map<String, Object>> problemList = problemDao.getMyProblemList(paramMap);
			returnMap.put("problemList", problemList);
			returnMap.put("pageNow", pageNow);

			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = problemDao.getMyProblemList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			returnMap.put("errFlag", "success");


		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  我的回答列表
	 * @throws IOException
	 */
	public Map<String, Object> getMyAnswerList(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			List<Map<String,Object>> courseList = new ArrayList<Map<String, Object>>();
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId","roleId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			int roleId = Integer.parseInt(String.valueOf(sessionMap.get("roleId")));
			returnMap.put("stuorteaId", stuorteaId);
			returnMap.put("roleId", roleId);
			paramMap.put("stuorteaId", stuorteaId);
			//查询问题列表
			List<Map<String, Object>> answerList = answerDao.getMyAnswerList(paramMap);
			returnMap.put("answerList", answerList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = answerDao.getMyAnswerList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			returnMap.put("errFlag", "success");
			//当前登陆人所属课程
			if(roleId==1){
				//说明是学生、
				//通过学生获取此学生所属课程
				courseList = myCourseDao.getStuCourse(paramMap);
			}if(roleId==2){
				//说明是教师
				//通过教师号获取此教师所属课程
				courseList = courseDao.getTeaTeachCourse(paramMap);
			}
			returnMap.put("courseList", courseList);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**isMark 0正常问题详情显示所有人的回答  1我的问题列表中详情 只显示我自己的回答
	 * @param 问题详情
	 * @throws IOException
	 */
	public Map<String, Object> getProblemDetail(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			//查询当前登陆人的基本信息
			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("excuseMark",memList.get(0).get("excuseMark"));
			//通过问题主键获取问题详情
			Map<String, Object> problemMap = problemDao.getProblemDetail(paramMap);
			returnMap.put("problemMap", problemMap);
			returnMap.put("pageNow", pageNow);
			//通过问题主键获取此问题的答案列表
			paramMap.put("stuorteaId",stuorteaId);
			List<Map<String,Object>> answerList = answerDao.getAllAnswerByProId(paramMap);
			returnMap.put("answerList", answerList);
			returnMap.put("stuorteaId", stuorteaId);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allanswerList = answerDao.getAllAnswerByProId(paramMap);
			int totalPage = pageUtil.getTotalPage(allanswerList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 *  回答问题表单提交。
	 * @throws IOException
	 */
	public boolean answerProblem(Map<String,Object> paramMap, HttpServletRequest request,HttpSession session) throws Exception {

		boolean flag = false;

		try {

//			String str = java.net.URLDecoder.decode(String.valueOf(paramMap.get("answerContent")),"UTF-8");
//			paramMap.put("answerContent", str);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			//去空格处理
//			paramMap.put("answerContent",String.valueOf(paramMap.get("answerContent")).trim());
			paramMap.put("stuorteaId",stuorteaId);
			/*if(PubMethods.isSpecialChar(String.valueOf(paramMap.get("answerContent")))){
				flag = false;
				logger.info("回答问题表单提交有特殊字符");
				return flag;
			}*/
			flag = answerDao.answerProblem(paramMap);
			if(flag){
				//查询回答当前问题的个数
				int count = answerDao.getAnsertCount(paramMap);
				paramMap.put("problemCount", count);
				//向问题表中插入当前问题回答的个数
				flag = problemDao.saveProblem(paramMap);
			}

		} catch (Exception e) {
			throw e;
		}
		return flag;
	}

	/**
	 *  删除我的回答问题。
	 * @throws IOException
	 */
	public boolean delAnswer(List<String> list) throws Exception {

		boolean flag = false;

		try {

			flag = answerDao.delAnswer(list);


		} catch (Exception e) {
			throw e;
		}
		return flag;
	}

	/**
	 *  删除我提问的问题。
	 * @throws IOException
	 */
	public boolean delProblem(List<String> list) throws Exception {

		boolean flag = false;

		try {
			flag = problemDao.delProblem(list);
			if(flag){
				//查询某问题下是否有回答
				List<Map<String,Object>> answerList = answerDao.getAllAnswerByProIdList(list);
				if(answerList.size()==0){
					return flag;
				}
				//删除问题下所有的回答
				flag = answerDao.delAnswerByPromId(list);
			}

		} catch (Exception e) {
			throw e;
		}
		return flag;
	}

	/**
	 *  提问问题表单提交。
	 * @throws IOException
	 */
	public Map<String,Object> putProblem(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		boolean flag = false;
		Map<String,Object> returnMap = new HashMap<String, Object>();
		String msg = "";
		try {
			//转义字符处理
//			String str = java.net.URLEncoder.encode(String.valueOf(paramMap.get("problemContent")),"UTF-8");
//			paramMap.put("problemContent", str);
			//获取当前登陆人的学号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId",stuorteaId);
			//去空格
			paramMap.put("problemName",String.valueOf(paramMap.get("problemName")).trim());
//			paramMap.put("problemContent",String.valueOf(paramMap.get("problemContent")).trim());
			//判断输入的问题标题是否超出限制
			if(String.valueOf(paramMap.get("problemName")).trim().length()>30){
				msg = "输入有特殊字符";
				returnMap.put("flag",false);
				returnMap.put("msg","问题标题长度超出限制");
				return returnMap;
			}
			if(PubMethods.isSpecialChar(String.valueOf(paramMap.get("problemName")))){
				flag = false;
				logger.info("提问问题表单提交有特殊字符");
				msg = "输入有特殊字符";
				returnMap.put("flag",flag);
				returnMap.put("msg",msg);
				return returnMap;
			}
			//判断当前人是否已经提过相同问题
			Map<String,Object> myMap = problemDao.getMyProblemByNameOrsId(paramMap);
			if(myMap!=null){
				msg = "提问的问题已存在";
				returnMap.put("flag",false);
				returnMap.put("msg",msg);
				return returnMap;
			}
			if(paramMap.get("courseId")==null){
				msg = "请选择课程";
				returnMap.put("flag",false);
				returnMap.put("msg",msg);
				return returnMap;
			}
			flag = problemDao.putProblem(paramMap);
			returnMap.put("flag",flag);
			returnMap.put("msg",msg);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return 问题列表页面（学生）。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getStuAllProblemList(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//查询当前登陆人的基本信息
			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("excuseMark",memList.get(0).get("excuseMark"));
			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseDao.getStuCourse(paramMap);
			if(courseList.size()!=0&&courseList!=null){
				returnMap.put("courseList", courseList);
				paramMap.put("courseList", courseList);
				//查询问题列表(查询每个习题中回答的个数20171218改--回答问题的个数不从数据库中取，改成计算)
				List<Map<String, Object>> problemList = problemDao.getAllProblemList(paramMap);
				returnMap.put("problemList", problemList);
				returnMap.put("pageNow", pageNow);

				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = problemDao.getAllProblemList(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
			}else{
				returnMap.put("errFlag", "fail");
				returnMap.put("errMsg", "当前课程暂无问题");
				returnMap.put("totalPage", 0);
			}


		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return 问题列表页面（管理员）。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAdminAllProblemListByPost(Map<String, Object> paramMap, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);

			//查询所有课程
			List<Map<String,Object>> courseList = courseDao.getAllCourse(paramMap);
			returnMap.put("courseList", courseList);
			if(courseList.size()!=0&&courseList!=null){
				//查询问题列表(查询每个习题中回答的个数20171218改--回答问题的个数不从数据库中取，改成计算)
				List<Map<String, Object>> problemList = problemDao.getAdminAllProblemListByPost(paramMap);
				returnMap.put("problemList", problemList);
				returnMap.put("pageNow", pageNow);

				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = problemDao.getAdminAllProblemListByPost(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
			}else{
				returnMap.put("errFlag", "fail");
				returnMap.put("errMsg", "当前课程暂无问题");
				returnMap.put("totalPage", 0);
			}


		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 *  禁言帖子。
	 * @throws IOException
	 */
	public Map<String,Object> excuseProblem(Map<String, Object> paramMap) throws Exception {

		boolean flag = false;
		Map<String,Object> returnMap = new HashMap<String, Object>();
		String msg = "";
		try {
			flag = problemDao.excuseProblem(paramMap);
			returnMap.put("flag",flag);
			returnMap.put("msg",msg);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	public boolean answerProblemOther(Map<String,Object> paramMap, HttpServletRequest request,HttpSession session) throws Exception {

		boolean flag = false;

		try {

//			String str = java.net.URLDecoder.decode(String.valueOf(paramMap.get("answerContent")),"UTF-8");
//			paramMap.put("answerContent", str);
			//获取当前登陆人的学号/工号
			SysUser user = (SysUser) session.getAttribute(USER_INFO);
//			returnMap.put("stuorteaId", stuorteaId);
//			paramMap.put("stuorteaId", stuorteaId);
			//查询当前登陆人的基本信息
//			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			if (user==null) {
				return flag;
			}
			String stuorteaId = user.getStuorteaId();
			paramMap.put("stuorteaId",stuorteaId);
			flag = answerDao.answerProblemMoble(paramMap);
			if(flag){
				//查询回答当前问题的个数
				int count = answerDao.getAnsertCount(paramMap);
				paramMap.put("problemCount", count);
				//向问题表中插入当前问题回答的个数
				flag = problemDao.saveProblem(paramMap);
			}

		} catch (Exception e) {
			throw e;
		}
		return flag;
	}
	public Map<String, Object> getProblemDetailOther(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			SysUser user = (SysUser) session.getAttribute(USER_INFO);
//			returnMap.put("stuorteaId", stuorteaId);
//			paramMap.put("stuorteaId", stuorteaId);
			//查询当前登陆人的基本信息
//			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			if (user==null) {
				returnMap.put("result", "fail");
				returnMap.put("data", "登陆信息获取失败");
				return returnMap;
			}
			String stuorteaId = user.getStuorteaId();
			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("excuseMark",memList.get(0).get("excuseMark"));
			//通过问题主键获取问题详情
			Map<String, Object> problemMap = problemDao.getProblemDetail(paramMap);
			returnMap.put("problemMap", problemMap);
			returnMap.put("pageNow", pageNow);
			//通过问题主键获取此问题的答案列表
			paramMap.put("stuorteaId",stuorteaId);
			List<Map<String,Object>> answerList = answerDao.getAllAnswerByProIdOther(paramMap);
			returnMap.put("answerList", answerList);
			returnMap.put("stuorteaId", stuorteaId);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allanswerList = answerDao.getAllAnswerByProIdOther(paramMap);
			int totalPage = pageUtil.getTotalPage(allanswerList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	public Map<String, Object> getAllProblemListOther(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
//			//获取当前登陆人的学号/工号
//			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			SysUser user = (SysUser) session.getAttribute(USER_INFO);
			String stuorteaId = user.getStuorteaId();
//			returnMap.put("stuorteaId", stuorteaId);
//			paramMap.put("stuorteaId", stuorteaId);
			//查询当前登陆人的基本信息
//			List<Map<String,Object>> memList = memberDao.getMemberByStuorteaId(stuorteaId);
			if (user==null) {
				returnMap.put("result", "fail");
				returnMap.put("data", "登陆信息获取失败");
				return returnMap;
			}
			//查询问题列表(查询每个习题中回答的个数20171218改--回答问题的个数不从数据库中取，改成计算)
			List<Map<String, Object>> problemList = problemDao.getAllProblemListOther(paramMap);
			returnMap.put("problemList", problemList);
			returnMap.put("pageNow", pageNow);

			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = problemDao.getAllProblemListOther(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			returnMap.put("errFlag", "success");

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
}
